from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from blog.models import Article

# 返回视图的方法
def hello_world(request):
    return HttpResponse("Hello Django")


def article_content(request):
    article = Article.objects.all()[0]
    title = article.title
    brief_content = article.brief_content
    content = article.content
    article_id = article.article_id
    pubilsh_date = article.publish_date

    return_str = 'title: %s, brief_content: %s, content: %s, article_id: %s, pubilsh_date: %s,' % (title, brief_content, content, article_id, pubilsh_date)

    return HttpResponse(return_str)


# 渲染首页模板
def get_index_page(request):

    page_size = 5

    next_page = None
    prev_page = None

    page = request.GET.get('page')
    if page:
        page = int(page)
    else:
        page = 1

    print(page)

    all_article = Article.objects.all()
    top5_article_list = Article.objects.order_by('-publish_date')[:5]

    paginator = Paginator(all_article, page_size)
    page_num = paginator.num_pages
    page_article_list = paginator.page(page)

    # 判断是否有下一页
    if page_article_list.has_next():
        next_page = page + 1
    else:
        next_page = page

    # 判断是否有上一页
    if page_article_list.has_previous():
        prev_page = page - 1
    else:
        prev_page = page

    return render(request, 'blog/index.html', {
        'article_list': page_article_list,
        'page_num': range(1, page_num + 1),
        'curr_page': page,
        'next_page': next_page,
        'prev_page': prev_page,
        'top5_article_list': top5_article_list
    })


# 渲染详情模板
def get_detail_page(request, article_id):
    all_article = Article.objects.all()

    curr_article = None
    previous_article = None
    next_article = None
    previous_article_index = 0
    next_article_index = 0

    for index, article in enumerate(all_article):
        if index == 0:
            previous_article_index = 0
            next_article_index = index + 1

        elif index == len(all_article):
            previous_article_index = index - 1
            next_article_index = index

        else:
            previous_article_index = index - 1
            next_article_index = index + 1

        if article.article_id == article_id:
            curr_article = article
            previous_article = all_article[previous_article_index]
            next_article = all_article[next_article_index]
            break



    section_list = curr_article.content.split('\n')

    return render(request, 'blog/detail.html', {
        'curr_article': curr_article,
        'section_list': section_list,
        'previous_article': previous_article,
        'next_article': next_article,
    })
